package at.ltasat.classifier;

public final class Membership<D> implements Comparable<Membership<D>> {
	private final Clazz<D> clazz;
	private final double degree;

	public static void validate(Membership<?>[] memberships) {
		if (!check(memberships)) {
			throw new IllegalArgumentException("Sum of degrees must be 1!");
		}
	}

	public static boolean check(Membership<?>[] memberships) {
		final double epsilon = 0.001;
		double checksum = 0;
		for (Membership<?> membership : memberships) {
			checksum += membership.getDegree();
		}
		return !(checksum + epsilon < 1 || 1 < checksum - epsilon);
	}

	public Membership(Clazz<D> clazz, double degree) {
		assert clazz != null;
		assert degree >= 0 && degree <= 1 : String.valueOf(degree);
		this.clazz = clazz;
		this.degree = degree;
	}

	public Clazz<D> getClazz() {
		return clazz;
	}

	public double getDegree() {
		return degree;
	}

	@Override
	public int compareTo(Membership<D> other) {
		int result = -Double.compare(getDegree(), other.getDegree());
		if (result == 0) {
			result = Integer.compare(getClazz().getId(), other.getClazz().getId());
		}
		return result;
	}

	@Override
	public String toString() {
		return degree + ":" + clazz;
	}
}
